package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.WareInfoEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {


    @Resource
    private PurchaseDetailService purchaseDetailService;

    @Resource
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 列表status为0的采购单****
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", 0).or().eq("status", 1)

        );
        return new PageUtils(page);
    }

    /**
     * 合并采购项****
     */
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null){
            //新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId=purchaseEntity.getId();
        }
        //TODO 确认采购单状态是0,1才可以合并
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId=purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntityList = items.stream()
                .map(itemId -> {
                    PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                    purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                    purchaseDetailEntity.setId(itemId);
                    purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                    return purchaseDetailEntity;
                }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     *  领取采购单****
     */
    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> purchaseEntityList = ids.stream()
                .map(id -> {
                    PurchaseEntity purchaseEntity = this.getById(id);
                    return purchaseEntity;
                }).map(purchaseEntity -> {
                    if (purchaseEntity.getStatus().equals(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) ||
                            purchaseEntity.getStatus().equals(WareConstant.PurchaseStatusEnum.CREATED.getCode())) {
                        purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                        purchaseEntity.setUpdateTime(new Date());
                    }
                    return purchaseEntity;
                }).collect(Collectors.toList());

        //2、改变采购单的状态
        this.updateBatchById(purchaseEntityList);

        //3、改变采购项的状态
        purchaseEntityList.forEach(item-> {
                    List<PurchaseDetailEntity> entities =purchaseDetailService
                            .listDetailByPurchaseId(item.getId());
                    List<PurchaseDetailEntity> purchaseDetailEntityList = entities.stream()
                            .map(entity -> {
                                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                                purchaseDetailEntity.setId(entity.getId());
                                return purchaseDetailEntity;
                            }).collect(Collectors.toList());
                    purchaseDetailService.updateBatchById(purchaseDetailEntityList);
                });
    }

    /**
     *  完成采购****
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Long purchaseDoneVoId = purchaseDoneVo.getId();
        //2、改变采购项的状态
        boolean flag=true;
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();

        List<PurchaseDetailEntity> purchaseDetailEntityList = new ArrayList<>();
        for(PurchaseItemDoneVo item:items){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            Integer itemStatus = item.getStatus();
            if(itemStatus.equals(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode())){
                flag=false;
                detailEntity.setStatus(itemStatus);
            }else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                ////3、将成功采购的进行入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            purchaseDetailEntityList.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);

        //1、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVoId);
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():
                WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);
    }

}